﻿using Gobang.Client.Common;
using Gobang.Client.View.CustomControl;
using Gobang.ToolClass.Area;
using Sunny.UI;

namespace Gobang.Client.View.FrmPage
{
    public partial class CenterPage : UIPage
    {
        public readonly MainPage _mainPage;
        public CenterPage(MainPage mainPage)
        {
            InitializeComponent();
            _mainPage = mainPage;

            _mainPage.SelectRoom = SelectRoomMethod;

        }

        private List<ChessGameControl> desks = new List<ChessGameControl>();
        private void SelectRoomMethod(TreeViewEventArgs e)
        {
            if (e.Node.Parent == null)
                return;


            var area = e.Node.Tag as AreaNode;
            var rooms = AreaCache.FindDesks(area.AreaId);
            var preText = e.Node.Parent.Text;

            if (desks.Count > 0 && desks.Count == rooms.Count)
            {
                for (int i = 0; i < rooms.Count; i++)
                {
                    ChessGameControl chessGameControl = desks[i];
                    chessGameControl.SetGameName = preText + "-" + area.AreaName + "-" + rooms[i].RoomName;
                    chessGameControl.Node = area;
                    chessGameControl.Room = rooms[i];
                    chessGameControl.IsManMachine = preText.Contains("人机");
                }
                this.uiFlowLayoutPanel1.Validate();
            }
            else
            {
                DisposeDesks();
                foreach (var item in rooms)
                {
                    ChessGameControl chessGameControl = new ChessGameControl(preText + "-" + area.AreaName + "-" + item.RoomName, this);
                    chessGameControl.Node = area;
                    chessGameControl.Room = item;
                    chessGameControl.IsManMachine = preText.Contains("人机");
                    chessGameControl.Click += ChessGameControl_Click;
                    this.uiFlowLayoutPanel1.Add(chessGameControl);
                    desks.Add(chessGameControl);

                }
            }

        }

        private void ChessGameControl_Click(object? sender, EventArgs e)
        {
            _mainPage._frmMain.Hide();
            using (FrmGobangMain fgm = new FrmGobangMain(null))
            {
                fgm.ShowDialog();
            }
            _mainPage._frmMain.Show();
        }

        private void DisposeDesks()
        {
            if (desks.Count == 0)
                return;

            for (int i = 0; i < desks.Count; i++)
            {
                desks[i].Dispose();
            }
            desks.Clear();
        }

        private void CenterPage_FormClosing(object sender, FormClosingEventArgs e)
        {
            DisposeDesks();
        }

    }
}
